import pageination from '../../components/pageination/pageination.vue'
import urls from "../../common/js/api_url_array";
export default {
	data() {
			return {

        ProjectTerminate: false,

				//数据
        projectId: 0,

    logPage: 1,
    logTotal: 0,
				typeThe: '',
				type: '',
				modelShowView: false,
				isUpd: false,
				obj: {},
				id: 0,
				validate: {},
				expert: {},
				logData: [],
				projectObj: {},
				template: {},
				project: [], // table
				baseSelect: [],
				modelShow: false,
				ProjectModelShow: false,
				demandModelShow: false,
				WorkModelShow: false,
				total: 0, //总条数
				page: 1, //当前页
				size: 10, //每页显示条数
				uploadNum: 0,
				FileUpload: [],
				demandBookUrl: '', //需求书附件
				curId: 0,
				userId: this.get("userInfo").id,
				user: this.get("userInfo"),
				curIndex:-1,//选中下标
				baseTypes:[
					{id:0,name:"研究院项目"},
					{id:1,name:"横向项目"}
				]
			}
		},
		components: {
			pageination
		},
		created() { //调用方法
			let that = this;
			that.getBase();
			that.getTemplate();
		},
		mounted() {
			//加载表单验证
			this.validate = $("#projectForm").validate({
				ignore: [],
				rules: {
					areasId: {
						required: true
					},
					name: { // 名称
						required: true,
						maxlength: 50
					},
					type: { // 类型
						required: true,
					},

					introduction: {
						required: true,
						maxlength: 1000
					},
          demandBookUrl: {
            required: true,
          }
				},
				messages: {
					name: { // 名称
						required: '请填写项目名称',
						maxlength: '最多只能输入50个字！'
					},
					type: { // 名称
						required: '请选择项目类型',
					},

					introduction: {
						required: '请填写项目简介',
						maxlength: '最多只能输入1000个字!'
					},
					areasId: {
						required: '请选择基地',
					},
          demandBookUrl: {
            required: '请上传附件！',
          }
				},
				/*errorElement: "em",
				errorPlacement: function(error, element) {
					error.appendTo(element.parents(".error-box").children(".error-msg"));
				}*/
			});
		},
		methods: { //写函数方法
		//给选中的列加背景色
		choosed:function(index){
			this.curIndex=index;
		},
      closeWorkModel: function () {
        this.WorkModelShow = false;
      },

      pageFnExpertsLog: function(val, pid){
        this.logPage = parseInt(val);
        this.rorkRecord();
      },  //专家log

      /**返回子组件用户选择的一页显示条数**/
      obtainChildExpertsLog: function(data) {
        this.row = data;
      },

			//页码切换执行方法
			getProject: function() {
				let that = this;
				if (!that.userId) {
					return;
				};
				that.$post(
						that.urls.getBaseProject, {
							"id": that.userId,
							"pageNum": that.page,
							"pageSize": that.size
						}
					)
					.then(function(res) {
						if (res.success) {
							that.project = res.pageInfo.list;
							that.page = res.pageInfo.pageNum;
							that.total = res.pageInfo.total;
						}
					})
			},
			// 提交项目新增
			subProject: function() {

				let that = this;
				let flg = that.validate.form();
				if (!flg) {
					return;
				}
				let dataObj = that.combinationFormObject(that.validate.currentForm);

				$('#projectButton').attr('disabled', true);

				setTimeout(function(e) {
					$('#projectButton').attr('disabled', false);
				}, 3000);

				let urls;
				let msg;
				let errMsg;
				if (that.id) {
					urls = that.urls.updateProjectInfo;
					msg = '修改项目成功!';
					errMsg = '修改项目失败';
					dataObj.id = that.id;
				} else {
					urls = that.urls.addBaseProject;
					msg = '新增项目成功!';
					errMsg = '新增项目失败';
				};
				// 查重
				/*      that.$post(
				        that.urls.queryProjectHeavy,
				        dataObj
				      )
				        .then(function(res) {
				          if(res.success && res.data) {
				            layer.msg('该项目名称已存在!', {
				              time: 3000, //3s后自动关闭
				            });
				          }else {*/
				// 提交
				that.$post(
						urls,
						dataObj

					)
					.then(function(res) {
						if (res.success) {
							layer.msg(msg, {
								time: 3000, //3s后自动关闭
							});
							that.getProject();
							that.modelShow = false;

						} else {
							layer.msg(errMsg, {
								time: 3000, //3s后自动关闭
							});
						}
					})

			},
			pageFn: function(val, pid) {
				this.page = parseInt(val);
				this.getProject();
				//此处调列表数据接口
			},
			// 基地數據
			getBase: function() {
				let that = this;
				if (!that.userId) {
					return;
				};
				// 基地展示数据
				that.$post(
						that.urls.basePage, {
							"pageNum": 0,
							"list": [1, 5, 2],
							"pageSize": 9999999,
							"userId": that.userId
						}
					)
					.then(function(res) {
						if (res.success) {
							if (res.pageInfo.list.length > 0) {
								let arr = [];
								res.pageInfo.list.forEach(function(e) {
									if (e.status === 1 || e.status === 5 || e.status === 2) {
										arr.push({
											"id": e.id,
											"name": e.name
										});
									}
								})
								that.baseSelect = arr;

							}

						}
					})
			},
      subStrThe: function (str) {
        if(str) {
          if (str.length > 10) {
            let s = str.substr(0, 8);
            return s + '...';
          } else {
            return str;
          }
        }

      },
      //工作记录
      rorkRecord: function(id) {
        let that = this;
        that.logData = [];
        console.log(id)
        if(id){
          that.logPage = 1;
          that.logId = id;
        }

        that.$post(
          that.urls.getLogPage,
          {"pageNum": that.logPage,
            "pageSize": 10, 	"projectId": that.projectId
          }
        )
          .then(function(res) {
            if(res.success) {
              that.logData = res.pageInfo.list;
              that.logPage = res.pageInfo.pageNum;
              that.logTotal = res.pageInfo.total;
            }
          })
        this.WorkModelShow = true;
      },


			/**返回子组件用户选择的一页显示条数**/
			obtainChild: function(data) {
				this.row = data;
			},
			touchOffIdInput(n) {
				this.uploadNum = n;
				if (n == 1) {
					$("#handIdFront").click();
				}
			},
			/**文件上传(多文件)js**/
			idFrontImg: function(event) {
				let that = this;
				let files = event.currentTarget.files;
				if (!that.fileGlobalFilter(files)) {
					return;
				}
				let formData = new FormData();
				for (let i = 0, len = files.length; i < len; i++) {
					formData.append('fileNames', files[i]);
				}
				let config = {
					headers: {
						'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
					}
				};
				that.$post(
						that.urls.upload,
						formData,
						config
					)
					.then(function(res) {
						if (res.success) {
							let fileInfos = res.data;
							let urls = [];
							//  let names = [];
							let enclosureList = []; // 查看
							for (let i = 0, len = fileInfos.length; i < len; i++) {
								urls.push(fileInfos[i].url);
								//   names.push(that.getFileName(fileInfos[i].url));
								enclosureList.push({
									"name": that.getFileName(fileInfos[i].url),
									"url": fileInfos[i].url
								});

							}
							that.FileUpload = enclosureList;
							that.demandBookUrl = urls.join(";");
							that.validate.resetForm();
						}
					})
				console.log()
			},
			//打开项目需求模态框
			openModal: function() {
        this.validate.resetForm();
				$('#areasIdThe').val("");
				$('#baseType').val("");
				this.type = '新增';
				this.typeThe = '创建';
				this.FileUpload = [];
				this.demandBookUrl = '';
				this.id = 0;
				this.obj = {};
				this.isUpd = true;
				this.modelShow = true;
			},
			//项目动态
			projectDetails: function(obj) {
				this.projectObj = obj;
        this.curId = 0;
				this.ProjectModelShow = true;
			},
			//对接专家
			demand: function(id) {
				let that = this;
				that.expert = {};
				that.projectId = id;
				that.$post(
						that.urls.getProjectExpert, {
							"id": id
						}
					)
					.then(function(res) {
						if (res.success) {
							that.expert = res.data;
						}

					})
				that.demandModelShow = true;
			},
			//关闭模态框
			closeModel: function() {
			  this.ProjectTerminate = false;
				this.modelShowView = false;
				this.modelShow = false;
				this.ProjectModelShow = false;
				this.demandModelShow = false;
				this.WorkModelShow = false;
			},

			//下载资源
			downloadResources: function(filePath) {
				if (filePath != null && filePath != "") {
					window.location.href = this.urls.download + "?path=" + filePath;
				} else {
					layer.msg('暂无附件', {
						time: 3000, //3s后自动关闭
					});
				}
			},

			// 跳转到预览
			toSrc: function(url) {
				if (url == null || url == undefined || url == '') {
					layer.msg('暂无附件', {
						time: 3000, //3s后自动关闭
					});
					return;
				}
				window.open(urls.baseUrl + url);
			},
      // 跳转到预览
      toSrcThe: function(url) {
        if (url == null || url == undefined || url == '') {
          layer.msg('暂无附件', {
            time: 3000, //3s后自动关闭
          });
          return;
        }
        window.open(url);
      },
			// del att
			delAtts: function() {
				this.demandBookUrl = '';
				this.FileUpload = [];
			},
			subStr: function(str) {
				if (str.length > 10) {
					let s = str.substr(0, 7);
					return s + '...';
				} else {
					return str;
				}
			},

			// 发布，
			edit: function(id) {
				let that = this;
				that.$post(
						that.urls.projectRelease, {
							"id": id
						}
					)
					.then(function(res) {
						if (res.success) {
							layer.msg('发布项目成功！', {
								time: 3000, //3s后自动关闭
							});
							that.getProject();
						} else {
							layer.msg('发布项目失败！', {
								time: 3000, //3s后自动关闭
							});
						}
					})
			},
			// del
			delThe: function(id) {
				let that = this;
				layer.confirm('你确定要删除吗?', {
					icon: 3,
					title: '提示'
				}, function(index) {

					if (id) {

						that.$post(
								that.urls.deleteProjectInfo, {
									"id": id
								}
							)
							.then(function(res) {
								if (res.success) {
									layer.msg('删除项目成功！', {
										time: 3000, //3s后自动关闭
									});
									that.getProject();
								} else {
									layer.msg('删除项目失败！', {
										time: 3000, //3s后自动关闭
									});
								}
							})

					}

				});

			},
			// 修改
			editThe: function(id) {
        this.validate.resetForm();
				$('#areasId').val("");
				$('#type').val("");
				let that = this;
				that.type = '修改';
				that.typeThe = '修改';
				that.id = id;
				that.modelShow = true;
				that.isUpd = true;
				that.obj = {};
				that.$post(
						that.urls.queryProject, {
							"id": id
						}
					)
					.then(function(res) {
						if (res.success) {
							that.obj = res.data;
							$('#areasIdThe').val(res.data.areasId);
							$('#typeThe').val(res.data.type);
							that.demandBookUrl = res.data.demandBookUrl;
							let enclosureList = []; // 查看
							enclosureList.push({
								"name": that.getFileName(that.getFileName(res.data.demandBookUrl)),
								"url": res.data.demandBookUrl
							});
							that.FileUpload = enclosureList;

						}
					})
			},

			// view
			viewProject: function(id) {
				let that = this;
				that.id = id;

				that.modelShowView = true;
				that.isUpd = false;
				that.obj = {};
				that.$post(
						that.urls.queryProject, {
							"id": id
						}
					)
					.then(function(res) {
						if (res.success) {
							that.obj = res.data;
							that.demandBookUrl = res.data.demandBookUrl;
							let enclosureList = []; // 查看
							enclosureList.push({
								"name": that.getFileName(that.getFileName(res.data.demandBookUrl)),
								"url": res.data.demandBookUrl
							});
							that.FileUpload = enclosureList;

						}
					})
			},
			//获取模板信息
			getTemplate: function() {
				let that = this;
				//模板类型(0：其他;1:基地申请；2：项目申报；3：项目申请；4：合作合同；5：任务书；6：中期报告；7：结题报告)
				that.$post(
						that.urls.getTemplate, {
							"type": 2
						}
					)
					.then(function(res) {
						if (res.success) {
							that.template = res.data;
						}
					})
			},
			//项目需求书模板下载
			download: function() {
				let url = this.template.url;
				if (url == null || url == "") {
					layer.msg("请联系管理员上传【项目申请书】", {
						time: 3000, //3s后自动关闭
					});
					return;
				}
				window.location.href = this.urls.download + "?path=" + url;
			},

			projectModel: function (obj) {
			  console.log(obj)
        this.ProjectTerminate = true;
			   this.projectObj = obj;

      }


		}
}
